package com.scalar.chiptrack.sales.actions;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.Address;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.commons.Labels;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.operations.packingslip.PackingSlipComparator;
import com.scalar.chiptrack.sales.*;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.chiptrack.sales.dao.NewSalesOrderDAO;
import com.scalar.chiptrack.sales.dao.SalesDAO;
import com.scalar.chiptrack.sales.dao.SalesOrderDAO;
import com.scalar.chiptrack.sales.forms.ApproverOrderForm;
import com.scalar.chiptrack.users.Functionality;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.utils.PDFGenerator;
import com.scalar.chiptrack.utils.StringUtils;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.MessageResources;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.*;

/**
 * Implementation of <strong>Action</strong> that gives customers list,
 * search with customer name, create sales order
 *
 * @author Kesava Kumar Achanala
 * @version $Revision: 1.14 $ $Date: 2011/02/01 23:39:43 $
 */

public final class OrderAction extends ChipTrackAction
{


    // ----------------------------------------------------- Instance Variables

    private static final String ACTION_NAME = "/order.do";  // Added by Basha (08/08/2003)
    public ApproverOrderForm subform;

    // --------------------------------------------------------- Public Methods


    /**
     * Process the specified HTTP request, and create the corresponding HTTP
     * response (or forward to another web component that will create it).
     *
     * @param mapping The ActionMapping used to select this instance
     * @param form The optional ActionForm bean for this request (if any)
     * @param request The HTTP request we are processing
     * @param response The HTTP response we are creating
     *
     * @exception Exception if business logic throws an exception
     */
    public ActionForward execute ( ActionMapping mapping,
                                   ActionForm form,
                                   HttpServletRequest request,
                                   HttpServletResponse response )
            throws Exception
    {

        subform = ( ApproverOrderForm ) form;
        String action = request.getParameter ( "action" );
        HttpSession session = request.getSession ();
        User users = ( User ) session.getAttribute ( SessionKeys.USER_KEY );
        if ( users == null )
        {
            session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?" + request.getQueryString () );
            return ( mapping.findForward ( "login" ) );
        }
        LineItem lineitem = new LineItem ();

        // Validate the request parameters specified by the user
        ActionErrors errors = new ActionErrors ();

        String salesOrderId = "";
        try
        {
            salesOrderId = request.getParameter ( "salesOrderId" );
        }
        catch ( NullPointerException e )
        {
            salesOrderId = "";
        }
        String salesOrderNo = request.getParameter ( "salesOrderNo" );
        if ( ( salesOrderId != null ) || ( salesOrderNo != null ) )
        {
            if ( subform == null )
                subform = new ApproverOrderForm ();

            String isSales = request.getParameter ( "isSales" );
            SalesOrder salesOrder = null;

            if ( salesOrderId != null )
            {
                if ( ( isSales != null ) && ( isSales.equals ( "FALSE" ) ) )
                {
                    salesOrder = SalesOrderDAO.loadOnlineOrder ( salesOrderId );
                }
                else
                {
                    try
                    {
                        salesOrder = SalesOrderDAO.loadSalesOrder ( salesOrderId );
                    }
                    catch( Exception e )
                    {
                        HashMap errorMessages = new HashMap();
                        errorMessages.put( ERROR_SALES_ORDER_INFORMATION_MISSING, null );
                        request.setAttribute ( SessionKeys.ERROR_MESSAGES, errorMessages );
                        if( "cancelledOrder".equals( action ) )
                        {
                            return mapping.findForward( "cancelledOrderSearch" ); //returning to the search screen
                        }
                        else
                        {
                            return mapping.findForward( "viewOrderSearch" ); //returning to the search screen
                        }
                    }
                }
            }
            else if ( salesOrderNo != null )
            {
                salesOrder = SalesOrderDAO.loadSalesOrderBySalesOrderNo ( salesOrderNo );

            }
            if ( salesOrder.getIsSample() == false && users.isActionAllowed( Functionality.SALES_VIEW_ORDER, User.USER_ACTION_MODIFY ) )
            {
                request.setAttribute ( "showMessage", "FALSE" );
            }
            else if ( salesOrder.getIsSample() && users.isActionAllowed( Functionality.SAMPLE_VIEW_ORDER, User.USER_ACTION_MODIFY ) )
            {
                request.setAttribute ( "showMessage", "FALSE" );
            }
            else
            {
                request.setAttribute ( "showMessage", "TRUE" );
            }

            // Added by Veeru on 23rd Nov 2004
            if ( salesOrder != null ) {
                Customer customer = new Customer();
                customer.setCustomerId( salesOrder.getCustomerId() );
                CustomerDAO.getCustomerDetailsForAcknowledgement( null, customer );
                request.setAttribute ( "customer", customer );
            }
            // End of Added by Veeru

            // Prabhanjan (30 Mar 2004)
            /*Commented by veeru on 16th June 2004
            if ( (! salesOrder.getEndUser ().trim ().equals ( "" ) ) )
            {
                System.out.println("End User Exists"+salesOrder.getEndUser());
                int endUserId = EndUserDAO.getEndUserIdByName ( salesOrder.getEndUser (), salesOrder.getCustomerId () );
                //EndUser endUser = EndUserDAO.getEndUserDetails ( endUserId );
                //salesOrder.setBillingAddressId ( endUser.getDefaultBillingAddressId () );
                //salesOrder.setShippingAddressId ( endUser.getDefaultShippingAddressId () );
                //salesOrder.setBillingAddress ( SalesOrder.getAddressAsString ( endUser.getBillingAddress () ) );
                //salesOrder.setShippingAddress ( SalesOrder.getAddressAsString ( endUser.getShippingAddress () ) );
                //salesOrder.setBillingAddressAsObject ( endUser.getBillingAddress () );
                //salesOrder.setShippingAddressAsObject ( endUser.getShippingAddress () );
                // Commented by veeru on 16th June 2004
                ApproveOrderAction.loadEndUserContactPersonDetails ( salesOrder, endUserId );
            }*/

            //Get the Holds for this orderId
            HashMap holds = SalesDAO.loadHoldsForOrder ( salesOrder.getSalesOrderId () );

            Iterator holdBy = holds.keySet ().iterator ();
            Iterator user = holds.values ().iterator ();


            //Loop thru the hold list and set the holds in the form
            while ( holdBy.hasNext () )
            {
                String holdedBy = ( String ) holdBy.next ();

                if ( holdedBy.equalsIgnoreCase ( "Finance" ) )
                {
                    subform.setFinanceHold ( true );
                    subform.setFinanceHoldUser ( ( String ) user.next () );
                }
                else if ( holdedBy.equalsIgnoreCase ( "Operations" ) )
                {
                    subform.setOperationsHold ( true );
                    subform.setOperationsHoldUser ( ( String ) user.next () );
                }
                else if ( holdedBy.equalsIgnoreCase ( "Sales" ) )
                {
                    subform.setSalesHold ( true );
                    subform.setSalesHoldUser ( ( String ) user.next () );
                }
                else if ( holdedBy.equalsIgnoreCase ( "Marketing" ) )
                {
                    subform.setMarketingHold ( true );
                    subform.setMarketingHoldUser ( ( String ) user.next () );
                }
            }
            //  System.out.println("Status3");

            //Load the reason codes in request

            request.setAttribute ( "marketingReasonCodes", SalesDAO.loadMarketingReasonCodes () );
            request.setAttribute ( "salesReasonCodes", SalesDAO.loadSalesReasonCodes () );
            request.setAttribute ( "financeReasonCodes", SalesDAO.loadFinanceReasonCodes () );
            request.setAttribute ( "opsReasonCodes", SalesDAO.loadOpsReasonCodes () );


            //Set the salesOrder into FormBean
            subform.setSalesOrderId ( salesOrder.getSalesOrderId () );
            subform.setSalesOrderNo ( salesOrder.getSalesOrderNo () );

            int customerId = SalesOrderDAO.loadCustomerId ( salesOrder.getSalesOrderId () );

            //subform.setSalesOrder(salesOrder);
            //request.setAttribute("approverOrderForm",subform);

            //Set the current order lineItems
            if ( ( isSales != null ) && ( isSales.equals ( "FALSE" ) ) )
            {
                request.setAttribute ( "lineItems",
                                       SalesOrderDAO.loadOnlineOrderLineItems ( salesOrder.getSalesOrderId () ) );
            }
            else
            {
                //Modified by sarada on 20th Jan 2004 to get customer part numbers
                //ArrayList cancelledList = SalesOrderDAO.loadCancelledOrderLineItems(salesOrder.getSalesOrderId());
                ArrayList cancelledList = SalesOrderDAO.loadCancelledOrderLineItemsByCustomerId ( salesOrder.getSalesOrderId (), customerId );
                if ( cancelledList.size () == 0 )
                    request.setAttribute ( "cancelledShow", "FALSE" );
                else
                    request.setAttribute ( "cancelledShow", "TRUE" );

                ArrayList changedList = SalesOrderDAO.loadOnlyChangeOrderLineItems ( salesOrder.getSalesOrderId () );
                if ( changedList.size () == 0 )
                    request.setAttribute ( "changedShow", "FALSE" );
                else
                    request.setAttribute ( "changedShow", "TRUE" );

                //Modified by sarada on 20th Jan 2004 to get customer part numbers
                //ArrayList presentList = SalesOrderDAO.loadOrderLineItems(salesOrder.getSalesOrderId());
                ArrayList presentList = SalesOrderDAO.loadOrderLineItemsByCustomerId ( salesOrder.getSalesOrderId (), customerId );
                // Prabhanjan (22 Mar 2004)
               /* if ( !( salesOrder.getEndUser ().trim ().equals ( "" ) ) )
                {
                    int endUserId = EndUserDAO.getEndUserIdByName ( salesOrder.getEndUser (), salesOrder.getCustomerId () );
                    SalesOrderDAO.loadEndUserPartNumbersForLineItems ( null, presentList, endUserId );
                    SalesOrderDAO.loadEndUserPartNumbersForLineItems ( null, changedList, endUserId );
                    SalesOrderDAO.loadEndUserPartNumbersForLineItems ( null, cancelledList, endUserId );
                }

                //Added by varma to load the ODM Part numbers if Odm exists for the salesorser
                if ( salesOrder.getOdm() != null && !( salesOrder.getOdm().trim().equals( "" ) ) )
                {

                    SalesOrderDAO.loadEndUserPartNumbersForLineItems ( null, presentList, salesOrder.getOdmId() );
                    SalesOrderDAO.loadEndUserPartNumbersForLineItems ( null, changedList, salesOrder.getOdmId() );
                    SalesOrderDAO.loadEndUserPartNumbersForLineItems ( null, cancelledList, salesOrder.getOdmId() );
                }*/
                //Modified by varma 12 Dec 2004
                /*if ( !( salesOrder.getEndUser ().trim ().equals ( "" ) ) )
                {
                    int endUserId = EndUserDAO.getEndUserIdByName ( salesOrder.getEndUser (), salesOrder.getCustomerId () );
                    SalesOrderDAO.loadEndUserPartNumbersForLineItems ( null, presentList, endUserId );
                    SalesOrderDAO.loadEndUserPartNumbersForLineItems ( null, changedList, endUserId );
                    SalesOrderDAO.loadEndUserPartNumbersForLineItems ( null, cancelledList, endUserId );
                }
                else
                {*/
                //SalesOrderDAO.loadCustomerPartNumbersForLineItems ( null, presentList, salesOrder.getCustomerId (), salesOrder.getOdmId() );
                //SalesOrderDAO.loadCustomerPartNumbersForLineItems ( null, changedList, salesOrder.getCustomerId (), salesOrder.getOdmId() );
                //SalesOrderDAO.loadCustomerPartNumbersForLineItems ( null, cancelledList, salesOrder.getCustomerId (), salesOrder.getOdmId() );
                NewSalesOrderDAO.loadOdmLabelNumbersForLineItems ( null, presentList, salesOrder.getCustomerId(), salesOrder.getOdmId());
                NewSalesOrderDAO.loadOdmLabelNumbersForLineItems ( null, changedList, salesOrder.getCustomerId(), salesOrder.getOdmId());
                NewSalesOrderDAO.loadOdmLabelNumbersForLineItems ( null, cancelledList, salesOrder.getCustomerId(), salesOrder.getOdmId());
                //}
                 //Added by Sarada on 24th June to get the COOL_Status
                String lastStatus[] = new String[presentList.size ()];
                int totalQty = 0;
                //float totalAmt = 0.0f;
                //float salesTax = 0.0f;
				double totalAmt = 0.0;
				double salesTax = 0.0;
                // Moved below 3 lines from inside the for loop to above the for loop by veeru on 10th June 2004
                float taxvalue = SalesOrderDAO.getTaxValue ( null, salesOrder.getSalesTaxType () );
                Float ff = new Float(taxvalue);
                double tax = ff.doubleValue();

                for ( int i = 0; i < presentList.size (); i++ )
                {

                    LineItem templineItem = ( LineItem ) presentList.get ( i );
                    coolstatus = templineItem.getStatus ();
                    lastStatus[i] = coolstatus;
                    totalQty = totalQty + templineItem.getQuantity ();
                    totalAmt = totalAmt + templineItem.getAmountAsDouble ();
                    //float taxvalue = SalesOrderDAO.getTaxValue ( null, salesOrder.getSalesTaxType () );

                    if ( templineItem.getIsTaxable () )
                    {
						//Float ff = new Float(taxvalue);
						//double tax = ff.doubleValue();
                        //salesTax = salesTax + ( templineItem.getAmount () * ( taxvalue / 100 ) );
						salesTax = salesTax + ( templineItem.getAmountAsDouble () * ( tax / 100 ) );
                    }

                }


                /*salesOrder.setSubTotal ( totalAmt );
                salesOrder.setSalesTax ( salesTax );
                salesOrder.setOrderTotal ( totalAmt + salesTax + salesOrder.getMisc () + salesOrder.getFrieght () );
                */
				salesOrder.setSalesTaxAsDouble(salesTax );
				salesOrder.setSubTotalAsDouble(totalAmt);
				salesOrder.setOrderTotalAsDouble(salesOrder.getSubTotalAsDouble()+salesOrder.getFrieghtAsDouble()+salesOrder.getMiscAsDouble()+salesOrder.getSalesTaxAsDouble());

                // Added by veeru on 13th April 2004
				//if ("change".equals(request.getParameter("prevAction")) )
				salesOrder.setChangeNumber ( SalesOrderDAO.loadChangeNo ( salesOrder.getSalesOrderId () ) - 1 );

                subform.setSalesOrder ( salesOrder );

                request.setAttribute ( "approverOrderForm", subform );

                request.setAttribute ( "lineitemstatus", lastStatus );


                if ( presentList.size () == 0 )
                    request.setAttribute ( "presentShow", "FALSE" );
                else
                    request.setAttribute ( "presentShow", "TRUE" );

                request.setAttribute ( "lineItems", presentList );
                request.setAttribute ( "lineItemsWithSubtotals", SalesOrderAction.loadLineItemsWithSubTotals ( ( ArrayList ) request.getAttribute ( "lineItems" ) ) );

                request.setAttribute ( "changeLineItems", changedList );
                request.setAttribute ( "cancelledLineItems", cancelledList );
                request.setAttribute ( "cancelledLineItemsWithSubTotals", SalesOrderAction.loadLineItemsWithSubTotals ( cancelledList ) );

            }

            //Put the lineItem holds in the request..
            request.setAttribute ( SessionKeys.INFO_MESSAGES, SalesDAO.loadLineItemHolds ( salesOrder.getSalesOrderId () ) );
            request.setAttribute ( SessionKeys.ERROR_MESSAGES, SalesDAO.loadHoldCancelledLineItems ( salesOrder.getSalesOrderId () ) );
            request.setAttribute ( "termsAndConditions", SalesDAO.loadTermsAndConditionsAsList () );

            //return to the approver page, where approver can approve/reject

            if ( "printOrder".equalsIgnoreCase ( action ) )
            {
                ArrayList linaItemList =  ( ArrayList ) request.getAttribute ( "lineItems" );
                //Added by Rohan on August 29th 2003 for sorting the line items based on PO Line Item Number
                if ( request.getAttribute ( "lineItems" ) != null )
                    Collections.sort ( linaItemList, new PackingSlipComparator () );
                //NewSalesOrderDAO.loadLineItemsWithCustomerAndOdmPartNumbers( null, linaItemList, salesOrder.getCustomerId(),salesOrder.getOdmId() );


                //Added by Prabhanjan on 07 Mar 2004
                //request.setAttribute ( "lineItemsWithSubtotals", loadLineItemsWithSubTotals ( linaItemList ) );

                if ( request.getAttribute ( "changeLineItems" ) != null )
                    Collections.sort ( ( ArrayList ) request.getAttribute ( "changeLineItems" ), new PackingSlipComparator () );
                if ( request.getAttribute ( "cancelledLineItems" ) != null )
                    Collections.sort ( ( ArrayList ) request.getAttribute ( "cancelledLineItems" ), new PackingSlipComparator () );
                //End of additions by Rohan on August 29th 2003


                if( Constants.CLIENT_NAME_AIRGO .equalsIgnoreCase( salesOrder.getClientName() ) )
                {
                    NewSalesOrderDAO.loadLineItemsWithCustomerAndOdmPartNumbers( null, linaItemList, salesOrder.getCustomerId(),salesOrder.getOdmId() );
                    request.setAttribute ( "lineItemsWithSubtotals", loadLineItemsWithSubTotalsForAirgo ( linaItemList ) );
                    return ( mapping.findForward ( "printOrderAirgo" ) );
                }
                else
                {
                    request.setAttribute ( "lineItemsWithSubtotals", loadLineItemsWithSubTotals ( linaItemList ) );
                    return ( mapping.findForward ( "printOrder" ) );
                }
            }

            if ( "customerOrder".equalsIgnoreCase ( action ) )
            {
                return ( mapping.findForward ( "customerOrder" ) );
            }

            if ( "cancelledOrder".equalsIgnoreCase ( action ) )
            {
                return ( mapping.findForward ( "cancelledOrder" ) );
            }

            if ( "salesOrderView".equalsIgnoreCase ( action ) )
            {
                return ( mapping.findForward ( "salesOrderView" ) );
            }

            // added by prabhanjan on 31st October 2003
            if ( "salesOrderViewMain".equalsIgnoreCase ( action ) )
            {
                return ( mapping.findForward ( "salesOrderViewMain" ) );
            }
            return ( mapping.findForward ( "viewOrder" ) );
        }

        return ( mapping.findForward ( "success" ) );
    }

    // Added by Prabhanjan on 31 Jan 2004 to get the PDF file
    public static String getSalesAckPDFFile ( String host, String salesOrderId ) throws ScalarException
    {
        String fileXMLPath = null;
        String filePDFPath = null;
        String fileXSLTPath = null;
        OutputStreamWriter out  = null;

        SalesOrder salesOrder = null;
        if ( salesOrderId != null )
        {
            salesOrder = SalesOrderDAO.loadSalesOrder ( salesOrderId );
        }

        int customerId = SalesOrderDAO.loadCustomerId ( salesOrder.getSalesOrderId () );
        ArrayList presentList = SalesOrderDAO.loadOrderLineItemsByCustomerId ( salesOrder.getSalesOrderId (), customerId );
        int odmId = salesOrder.getOdmId() ;
        //SalesOrderDAO.loadCustomerPartNumbersForLineItems ( null, presentList, customerId, odmId );
        if ( presentList != null )
        {
            Collections.sort ( presentList, new PackingSlipComparator () );
        }
        String saAsXML = formatAsXML ( salesOrder, presentList );

        if ( saAsXML == null )
        {
            return fileXMLPath;
        }

        FileWriter fWriter = null;
        File saPDFAttachment = null;
        File saXML = null;

        try
        {
            // CREATE TEMPORARY ATTACHMENT FILE
            String mailingTempDir = ConfigManager.getMailerTempDir ();
            File tempDir = new File ( mailingTempDir ).getCanonicalFile ();
            tempDir.mkdir ();

            String salesNo = salesOrder.getSalesOrderNo ();
            String xmlFileName, saAttachmentPDFFileName;
			if ( salesOrder.getIsSample () )
			{
				xmlFileName = "Sample Sales_Ack_" + salesNo + ".xml";
				saAttachmentPDFFileName = "Sample Sales_Ack_" + salesNo + ".pdf";
			}
			else
			{
				xmlFileName = "Sales_Ack_" + salesNo + ".xml";
				saAttachmentPDFFileName = "Sales_Ack_" + salesNo + ".pdf";
			}

            String xsltFileName = ConfigManager.getSalesOrderAckXml2PdfXslFile ();

            saXML = new File ( tempDir.getCanonicalPath (), xmlFileName );
            saXML.deleteOnExit ();

            saPDFAttachment = new File ( tempDir.getCanonicalPath (), saAttachmentPDFFileName );
            saPDFAttachment.deleteOnExit ();

            if ( ( saXML.exists () == true ) || ( saXML.createNewFile () == true ) )
            {
                /*fWriter = new FileWriter ( saXML, false );
                fWriter.write ( saAsXML );
                fWriter.close ();
                fWriter = null;*/

                out = new OutputStreamWriter( new FileOutputStream( saXML ), "UTF-8" );

                out.write ( saAsXML );
                out.close ();
                out = null;

                fileXMLPath = saXML.getCanonicalPath ().toLowerCase ();
                filePDFPath = saPDFAttachment.getCanonicalPath ().toLowerCase ();
                boolean success = PDFGenerator.convertXML2PDF ( fileXMLPath, xsltFileName, filePDFPath );

            }
        }
        catch ( Exception e )
        {
            System.out.println ( "Exception while creating Sales Order Ack PDF file" );
            e.printStackTrace ();
        }
        finally
        {
            if ( fWriter != null )
            {
                try
                {
                    fWriter.close ();
                    fWriter = null;
                }
                catch ( IOException ignore )
                {
                }
            }
            if( out != null )
			{
				try
				{
					out.close();
					out = null;
				}
				catch( IOException ignore ){}
			}
        }

        return filePDFPath;
    }

    public static String formatAsXML ( SalesOrder salesOrder, ArrayList presentList ) throws ScalarException
    {
        StringBuffer buf = new StringBuffer ( 2098 );
		salesOrder.setChangeNumber(SalesOrderDAO.loadChangeNo ( salesOrder.getSalesOrderId () )  - 1);
        String heading = null;
        String salesOrderNoFieldHeading = null;
        if ( salesOrder.getIsSample() )
        {
            heading = "Sample Order Acknowledgement";
            salesOrderNoFieldHeading = "Sample Sales Order#";
        }
        else
        {
            heading = "Sales Order Acknowledgement";
            salesOrderNoFieldHeading = "Sales Order#";
        }
        buf.append ( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "\n" );
        buf.append ( "<salesOrderAcknowledgement>" + "\n" );
        buf.append ( "<logo>" + ConfigManager.getChipTracImagesDir () + ConfigManager.getScalarLogo () + "</logo>" + "\n" );

        buf.append("<heading><![CDATA[" +heading+ "]]></heading>"+"\n");
        buf.append("<salesOrderNoFieldHeading><![CDATA[" +salesOrderNoFieldHeading+ "]]></salesOrderNoFieldHeading>"+"\n");

        buf.append ( "<selfAddress>" + "\n" );
        buf.append ( "<name><![CDATA[" + salesOrder.getClientName () + "]]></name>" + "\n" );
        Address clientAddress = salesOrder.getClientAddressAsObject ();

        buf.append ( "<address1><![CDATA[" + clientAddress.getAddress1 () + "]]></address1>" + "\n" );
        buf.append ( "<address2><![CDATA[" + clientAddress.getAddress2 () + "]]></address2>" + "\n" );
        buf.append ( "<address3><![CDATA[" + clientAddress.getAddress3 () + "]]></address3>" + "\n" );
        buf.append ( "<address4><![CDATA[" + clientAddress.getAddress4 () + "]]></address4>" + "\n" );
        StringBuffer cityStateZip = new StringBuffer ( "" );

        if ( !clientAddress.getCity ().equals ( "" ) ) cityStateZip.append ( clientAddress.getCity () + ", " );
        if ( !clientAddress.getState ().equals ( "" ) ) cityStateZip.append ( clientAddress.getState () + " - " );
        if ( !clientAddress.getZipCode ().equals ( "" ) ) cityStateZip.append ( clientAddress.getZipCode () + ", " );
        cityStateZip.append ( clientAddress.getCountry () );

        buf.append ( "<cityStateZip><![CDATA[" + cityStateZip + "]]></cityStateZip>" + "\n" );

        StringBuffer phFax = new StringBuffer ();
        if ( !clientAddress.getPhoneNumber ().equals ( "" ) ) phFax.append ( "Tel:" + clientAddress.getPhoneNumber () + ", " );
        if ( !clientAddress.getFaxNumber ().equals ( "" ) ) phFax.append ( "Fax:" + clientAddress.getFaxNumber () );

        buf.append ( "<phoneFax><![CDATA[" + phFax + "]]></phoneFax>" + "\n" );


        buf.append ( "</selfAddress>" + "\n" );

        Address address = salesOrder.getBillingAddressAsObject ();
        String customerName = salesOrder.getCustomerName ();
        if ( salesOrder.getCustomerName ().equals ( salesOrder.getBillingAddressAsObject().getContactPerson () ) )
        {
            customerName = null;
        }

        buf.append ( "<orderByAddress>" + "\n" );
        if( salesOrder.getBillingAddressAsObject().getContactPerson() != null && salesOrder.getCustomerName().trim().length() !=0 )
        {
            if( ! salesOrder.getBillingAddressAsObject().getContactPerson().equals( salesOrder.getCustomerName() ) )
            {
                buf.append ( "<name><![CDATA[" + customerName + "]]></name>" + "\n" );
            }
        }

        buf.append ( "<contactPerson><![CDATA[" + address.getContactPerson () + "]]></contactPerson>" + "\n" );
        buf.append ( "<address1><![CDATA[" + address.getAddress1 () + "]]></address1>" + "\n" );
        buf.append ( "<address2><![CDATA[" + address.getAddress2 () + "]]></address2>" + "\n" );
        buf.append ( "<address3><![CDATA[" + address.getAddress3 () + "]]></address3>" + "\n" );
        buf.append ( "<address4><![CDATA[" + address.getAddress4 () + "]]></address4>" + "\n" );

        buf.append ( "<city><![CDATA["+ address.getCity () + "]]></city>" + "\n" );
        buf.append ( "<stateZipCountry><![CDATA[" );
        if(address.getState ()!=null && !(address.getState ().equals("")))
        {
            buf.append(address.getState ());
        }
        if(address.getZipCode()!=null && !(address.getZipCode().equals("")))
        {
            if(address.getState ()!=null && !(address.getState ().equals("")))
            {
                buf.append(" - ");
            }
            buf.append(address.getZipCode());
        }
        if(address.getCountry ()!=null && !(address.getCountry ().equals("")))
        {
            if((address.getZipCode()!=null && !(address.getZipCode().equals("")))||(address.getState ()!=null && !(address.getState ().equals(""))))
            {
                buf.append(", ");
            }
            buf.append(address.getCountry ());
        }
        buf.append ( "]]></stateZipCountry>" + "\n" );
        buf.append ( "<phone><![CDATA[" + ( address.getPhoneNumber () != null && !address.getPhoneNumber().equals("") ?  "Tel:"+ address.getPhoneNumber () : "" ) + "]]></phone>" + "\n" );
        buf.append ( "<cell><![CDATA[" + ( address.getCellNumber () != null && !address.getCellNumber().equals("") ?  "Cell:"+address.getCellNumber () : "" ) + "]]></cell>" + "\n" );
        buf.append ( "<fax><![CDATA[" + ( address.getFaxNumber () != null && !address.getFaxNumber().equals("") ?  "Fax:" + address.getFaxNumber () : "" ) + "]]></fax>" + "\n" );
        buf.append ( "<email><![CDATA[" + ( address.getEmail () != null && !address.getEmail().equals("") ?  "EMail:" + address.getEmail () : "" ) + "]]></email>" + "\n" );
        buf.append ( "</orderByAddress>" + "\n" );

        buf.append ( "<billToAddress>" + "\n" );
        if( salesOrder.getBillingAddressAsObject().getContactPerson() != null && salesOrder.getCustomerName().trim().length() !=0 )
        {
            if( ! salesOrder.getBillingAddressAsObject().getContactPerson().equals( salesOrder.getCustomerName() ) )
            {
                buf.append ( "<name><![CDATA[" + customerName + "]]></name>" + "\n" );
            }
        }
        buf.append ( "<contactPerson><![CDATA[" + address.getContactPerson () + "]]></contactPerson>" + "\n" );
        buf.append ( "<address1><![CDATA[" + address.getAddress1 () + "]]></address1>" + "\n" );
        buf.append ( "<address2><![CDATA[" + address.getAddress2 () + "]]></address2>" + "\n" );
        buf.append ( "<address3><![CDATA[" + address.getAddress3 () + "]]></address3>" + "\n" );
        buf.append ( "<address4><![CDATA[" + address.getAddress4 () + "]]></address4>" + "\n" );

        buf.append ( "<city><![CDATA["+ address.getCity () + "]]></city>" + "\n" );
        buf.append ( "<stateZipCountry><![CDATA[" );
        if(address.getState ()!=null && !(address.getState ().equals("")))
        {
            buf.append(address.getState ());
        }
        if(address.getZipCode()!=null && !(address.getZipCode().equals("")))
        {
            if(address.getState ()!=null && !(address.getState ().equals("")))
            {
                buf.append(" - ");
            }
            buf.append(address.getZipCode());
        }
        if(address.getCountry ()!=null && !(address.getCountry ().equals("")))
        {
            if((address.getZipCode()!=null && !(address.getZipCode().equals("")))||(address.getState ()!=null && !(address.getState ().equals(""))))
            {
                buf.append(", ");
            }
            buf.append(address.getCountry ());
        }
        buf.append ( "]]></stateZipCountry>" + "\n" );
        buf.append ( "<phone><![CDATA[" + ( address.getPhoneNumber () != null && !address.getPhoneNumber().equals("") ?  "Tel:"+ address.getPhoneNumber () : "" ) + "]]></phone>" + "\n" );
        buf.append ( "<cell><![CDATA[" + ( address.getCellNumber () != null && !address.getCellNumber().equals("") ?  "Cell:"+address.getCellNumber () : "" ) + "]]></cell>" + "\n" );
        buf.append ( "<fax><![CDATA[" + ( address.getFaxNumber () != null && !address.getFaxNumber().equals("") ?  "Fax:" + address.getFaxNumber () : "" ) + "]]></fax>" + "\n" );
        buf.append ( "<email><![CDATA[" + ( address.getEmail () != null && !address.getEmail().equals("") ?  "EMail:" + address.getEmail () : "" ) + "]]></email>" + "\n" );

        buf.append ( "</billToAddress>" + "\n" );

        address = salesOrder.getShippingAddressAsObject ();

        buf.append ( "<shipToAddress>" + "\n" );
        buf.append ( "<name><![CDATA[" + salesOrder.getCustomerName () + "]]></name>" + "\n" );
        buf.append ( "<contactPerson><![CDATA[" + address.getContactPerson () + "]]></contactPerson>" + "\n" );
        buf.append ( "<address1><![CDATA[" + address.getAddress1 () + "]]></address1>" + "\n" );
        buf.append ( "<address2><![CDATA[" + address.getAddress2 () + "]]></address2>" + "\n" );
        buf.append ( "<address3><![CDATA[" + address.getAddress3 () + "]]></address3>" + "\n" );
        buf.append ( "<address4><![CDATA[" + address.getAddress4 () + "]]></address4>" + "\n" );

        buf.append ( "<city><![CDATA["+ address.getCity () + "]]></city>" + "\n" );
        buf.append ( "<stateZipCountry><![CDATA[" );
        if(address.getState ()!=null && !(address.getState ().equals("")))
        {
            buf.append(address.getState ());
        }
        if(address.getZipCode()!=null && !(address.getZipCode().equals("")))
        {
            if(address.getState ()!=null && !(address.getState ().equals("")))
            {
                buf.append(" - ");
            }
            buf.append(address.getZipCode());
        }
        if(address.getCountry ()!=null && !(address.getCountry ().equals("")))
        {
            if((address.getZipCode()!=null && !(address.getZipCode().equals("")))||(address.getState ()!=null && !(address.getState ().equals(""))))
            {
                buf.append(", ");
            }
            buf.append(address.getCountry ());
        }
        buf.append ( "]]></stateZipCountry>" + "\n" );
        buf.append ( "<phone><![CDATA[" + ( address.getPhoneNumber () != null && !address.getPhoneNumber().equals("") ?  "Tel:"+ address.getPhoneNumber () : "" ) + "]]></phone>" + "\n" );
        buf.append ( "<cell><![CDATA[" + ( address.getCellNumber () != null && !address.getCellNumber().equals("") ?  "Cell:"+address.getCellNumber () : "" ) + "]]></cell>" + "\n" );
        buf.append ( "<fax><![CDATA[" + ( address.getFaxNumber () != null && !address.getFaxNumber().equals("") ?  "Fax:" + address.getFaxNumber () : "" ) + "]]></fax>" + "\n" );
        buf.append ( "<email><![CDATA[" + ( address.getEmail () != null && !address.getEmail().equals("") ?  "EMail:" + address.getEmail () : "" ) + "]]></email>" + "\n" );

        buf.append ( "</shipToAddress>" + "\n" );

        buf.append ( "<information>" + "\n" );
        buf.append ( "<customerPO><![CDATA[" + salesOrder.getCustomerPO () + "]]></customerPO>" + "\n" );
        buf.append ( "<salesOrder><![CDATA[" + salesOrder.getSalesOrderNo () + "]]></salesOrder>" + "\n" );
        buf.append ( "<changeNumber><![CDATA[" + salesOrder.getChangeNumber () + "]]></changeNumber>" + "\n" );
        buf.append ( "<orderDate><![CDATA[" + salesOrder.getBookingdateAsString () + "]]></orderDate>" + "\n" );
        buf.append ( "<shipVia><![CDATA[" + salesOrder.getShippingMethod () + "]]></shipVia>" + "\n" );
        buf.append ( "<salesPerson><![CDATA[" + salesOrder.getSalesPerson () + "]]></salesPerson>" + "\n" );
        buf.append ( "<regionalRep><![CDATA[" + salesOrder.getRegionalRep () + "]]></regionalRep>" + "\n" );
        buf.append ( "<delTerms><![CDATA[" + salesOrder.getDeliveryTerms () + "]]></delTerms>" + "\n" );
        buf.append ( "<payTerms><![CDATA[" + ( salesOrder.getShippingTerms ().trim ().equals ( "-1" ) ? "" : salesOrder.getShippingTerms () ) + "]]></payTerms>" + "\n" );
        buf.append ( "</information>" + "\n" );
        buf.append ( "<comments><![CDATA[" + salesOrder.getComments () + "]]></comments>" + "\n" );

        LineItem lineItem = null;
        ArrayList presentListWithSubtotals = loadLineItemsWithSubTotals ( presentList );

        buf.append ( "<lineItems>" + "\n" );

        String mfgPartNumberLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.mfgPartNumber" );
        if ( mfgPartNumberLabel == null )
        {
            mfgPartNumberLabel = Labels.DEFAULT_MFG_PART_NUMBER_LABEL;
        }

		String mktgPartNumberLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.mktgPartNumber" );
        if ( mktgPartNumberLabel == null ) {
            mktgPartNumberLabel = Labels.DEFAULT_MKTG_PART_NUMBER_LABEL;
        }

        String customerPartNumberLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.customerPartNumber" );
        if ( customerPartNumberLabel == null )
        {
            customerPartNumberLabel = Labels.DEFAULT_CUSTOMER_PART_NUMBER_LABEL;
        }

        buf.append ( "<labelMfgPartNumber><![CDATA[" + mfgPartNumberLabel + "]]></labelMfgPartNumber>" );
        buf.append ( "<labelMktgPartNumber><![CDATA[" + mktgPartNumberLabel + "]]></labelMktgPartNumber>" );
        buf.append ( "<showMktgPartNumber><![CDATA[" + ConfigManager.getBooleanProperty(ConfigManager.PROP_SHOW_SALES_LINEITEM_MARKETING_PART_NUMBER) + "]]></showMktgPartNumber>" );
        buf.append ( "<labelCustPartNumber><![CDATA[" + customerPartNumberLabel + "]]></labelCustPartNumber>" );
        boolean lineItemsPresent = false;
        for ( int i = 0; i < presentListWithSubtotals.size (); i++ )
        {
            HashMap hashMap = ( HashMap ) presentListWithSubtotals.get ( i );
            Iterator iterator = hashMap.keySet ().iterator ();
            if( !hashMap.isEmpty())
            {
                lineItemsPresent = true;
            }
            while ( iterator.hasNext () )
            {
                ArrayList list = ( ArrayList ) iterator.next ();
                SubTotal subTotal = ( SubTotal ) hashMap.get ( list );
                String subTotalQty = subTotal.getSubTotalQty ();
                String subTotalAmt = subTotal.getSubTotalAmt ();


                int size = list.size ();
                buf.append ( "<group>" + "\n" );

                for ( int j = 0; j < size; j++ )
                {
                    lineItem = ( LineItem ) list.get ( j );
                    buf.append ( "<lineItem>" + "\n" );
                    buf.append ( "<poLineItem><![CDATA[" + lineItem.getPoLineItemNo () + "]]></poLineItem>" + "\n" );
                    buf.append ( "<reqQty><![CDATA[" + lineItem.getQtyAsString () + "]]></reqQty>" + "\n" );
                    buf.append ( "<remainingQty><![CDATA[" + lineItem.getToBeShippedQtyAsString () + "]]></remainingQty>" + "\n" );
                    buf.append ( "<um><![CDATA[" + "ea" + "]]></um>" + "\n" );
                    buf.append ( "<mfgPartNumber><![CDATA[" + lineItem.getManufacturingPartNo () + "]]></mfgPartNumber>" + "\n" );
					buf.append ( "<mktgPartNumber><![CDATA[" + lineItem.getMarketingPartNo () + "]]></mktgPartNumber>" + "\n" );
                    buf.append ( "<customerPartNumber><![CDATA[" + lineItem.getCustomerPartNo () + "]]></customerPartNumber>" + "\n" );
                    buf.append ( "<description><![CDATA[" + lineItem.getDescription () + "]]></description>" + "\n" );
                    buf.append ( "<requestDate><![CDATA[" + lineItem.getRequestDate () + "]]></requestDate>" + "\n" );
                    buf.append ( "<scheduleDate><![CDATA[" + lineItem.getScheduleDate () + "]]></scheduleDate>" + "\n" );
                    buf.append ( "<revisedShipDate><![CDATA[" + lineItem.getRevisedDate () + "]]></revisedShipDate>" + "\n" );
                    buf.append ( "<taxable><![CDATA[" + lineItem.getIsTaxableAsString () + "]]></taxable>" + "\n" );
                    buf.append ( "<expediteFee><![CDATA[" + ( ( lineItem.getIsExpedite () == true ) ? "Yes" : "No" ) + "]]></expediteFee>" + "\n" );
                    buf.append ( "<unitPrice><![CDATA[" + lineItem.getUnitPriceAsString () + "]]></unitPrice>" + "\n" );
                    buf.append ( "<extendedPrice><![CDATA[" + lineItem.getExtendedPriceAsString () + "]]></extendedPrice>" + "\n" );
                    buf.append ( "</lineItem>" + "\n" );
                }
                buf.append ( "<subTotalQty><![CDATA[" + subTotalQty + "]]></subTotalQty>" + "\n" );
                buf.append ( "<subTotalAmt><![CDATA[" + subTotalAmt + "]]></subTotalAmt>" + "\n" );
                buf.append ( "</group>" + "\n" );
            }
        }
        buf.append ( "</lineItems>" + "\n" );
        buf.append ("<lineItemsNotPresentMessage>");
        if( !lineItemsPresent )
        {
            buf.append("All the line items have been cancelled.");
        }
        buf.append("</lineItemsNotPresentMessage>");
        String end_user_Label = MessageResources.getMessageResources(Labels.APPLICATION_RESOURCE_PROPERTIES).getMessage("label.sales.endCustomer");
        if ( end_user_Label == null )
        {
            end_user_Label = "Error in End_Customer";
        }
        String end_customer_Label = MessageResources.getMessageResources(Labels.APPLICATION_RESOURCE_PROPERTIES).getMessage("label.sales.endUser");
        if ( end_customer_Label == null )
        {
            end_user_Label = "Error in End_user";
        }
        String quatation_No = MessageResources.getMessageResources(Labels.APPLICATION_RESOURCE_PROPERTIES).getMessage("label.sales.quotationNo");
        if ( quatation_No == null )
        {
            quatation_No = "Error in End_user";
        }

        buf.append ( "<end_user_Label><![CDATA[" + end_user_Label + "]]></end_user_Label>" );
        buf.append ( "<endUser><![CDATA[" + salesOrder.getOdm() + "]]></endUser>" + "\n" );

        buf.append ( "<end_customer_Label><![CDATA[" + end_customer_Label + "]]></end_customer_Label>" );
        buf.append ( "<endCustomer><![CDATA[" + salesOrder.getEndCustomer() + "]]></endCustomer>" + "\n" );

        buf.append ( "<quatation_no_label><![CDATA[" + quatation_No + "]]></quatation_no_label>" );
        if (salesOrder.getQuotationNo()== null)
        {
            buf.append ( "<quatationNo><![CDATA[" + "" + "]]></quatationNo>" + "\n" );
        }
        else
        {
            buf.append ( "<quatationNo><![CDATA[" + salesOrder.getQuotationNo() + "]]></quatationNo>" + "\n" );
        }

        buf.append ( "<total><![CDATA[" + salesOrder.getFinalSubTotalAsString () + "]]></total>" + "\n" );
        buf.append ( "<salesTax><![CDATA[" + salesOrder.getFinalSalesTaxAsString () + "]]></salesTax>" + "\n" );
        buf.append ( "<freight><![CDATA[" + salesOrder.getFrieghtAsString () + "]]></freight>" + "\n" );
        buf.append ( "<misc name=\"" + salesOrder.getMiscName () + "\"><![CDATA[" + salesOrder.getMiscAsString () + "]]></misc>" + "\n" );
        buf.append ( "<balanceDue><![CDATA[" + salesOrder.getFinalOrderTotalAsString () + "]]></balanceDue>" + "\n" );

        buf.append ( "<clientName><![CDATA[" + salesOrder.getClientName () + "]]></clientName>" );
        buf.append ( "<clientAddress><![CDATA[" + SalesOrder.getClientAddressToLoad ( clientAddress ) + "]]></clientAddress>" );
        if(ConfigManager.getShowTermsLabel() )
        {
            buf.append ( "<notes><termsLabel>" + Constants.TERMS_LABEL + "</termsLabel></notes>" );
        }



        ArrayList list = SalesDAO.loadTermsAndConditionsAsList ();
        if ( list != null )
        {
            buf.append ( "<termsAndConditions>" + "\n" );
            buf.append("<isTermsFromDB>"+ ConfigManager.getShowTermsFromDB() + "</isTermsFromDB>");
             buf.append ( "<termsPage1>" + ConfigManager.getChipTracImagesDir () + "/Terms and Condition of Sale.jpg</termsPage1>" + "\n" );
            buf.append ( "<termsfromdb>" + "\n" );

            for ( int i = 0; i < list.size (); i++ )
            {
                TermsAndConditions terms = ( TermsAndConditions ) list.get ( i );

                buf.append ( "<termAndConditionFromDB>" + "\n" );
                buf.append ( "<title><![CDATA[" + ( i + 1 ) + ". " + terms.getTermsTitle () + " ]]></title>" + "\n" );
                buf.append ( "<description>" + terms.getXMLFormatTerms(terms.getTerms ()) + "</description>" + "\n" );
                buf.append ( "</termAndConditionFromDB>" + "\n" );
            }
            buf.append ( "</termsfromdb>" + "\n" );
            buf.append ( "</termsAndConditions>" + "\n" );
        }
        


        buf.append ( "</salesOrderAcknowledgement>" + "\n" );

        return buf.toString ();
    }


    public static String getsalesAckHtmlFile ( String host, String salesOrderId ) throws ScalarException
    {
        String filePath = null;
        SalesOrder salesOrder = null;
        if ( salesOrderId != null )
        {
            salesOrder = SalesOrderDAO.loadSalesOrder ( salesOrderId );
        }
        int customerId = SalesOrderDAO.loadCustomerId ( salesOrder.getSalesOrderId () );
        ArrayList presentList = SalesOrderDAO.loadOrderLineItemsByCustomerId ( salesOrder.getSalesOrderId (), customerId );
        int odmId = salesOrder.getOdmId() ;
        //SalesOrderDAO.loadCustomerPartNumbersForLineItems ( null, presentList, customerId, odmId );
        if ( presentList != null )
        {
            Collections.sort ( presentList, new PackingSlipComparator () );
        }
        String psAsHtml = formatAsHTML ( host, salesOrder, presentList );

        if ( psAsHtml == null )
        {
            return filePath;
        }

        FileWriter fWriter = null;
        File psAttachment = null;

        try
        {
            // CREATE TEMPORARY ATTACHMENT FILE
            File tempDir = new File ( ConfigManager.getMailerTempDir() ).getCanonicalFile ();
            tempDir.mkdir ();

            String salesAttachmentFileName = null;
            String salesNo = salesOrder.getSalesOrderNo ();
			if ( salesOrder.getIsSample () )
			{
				salesAttachmentFileName = "Sample SalesOrder_ACK#  " + salesNo + ".html";
			}
			else
			{
            	salesAttachmentFileName = "SalesOrder_ACK#  " + salesNo + ".html";
			}
            psAttachment = new File ( tempDir.getCanonicalPath (), salesAttachmentFileName );
            psAttachment.deleteOnExit ();

            if ( ( psAttachment.exists () == true ) || ( psAttachment.createNewFile () == true ) )
            {
                fWriter = new FileWriter ( psAttachment, false );

                fWriter.write ( psAsHtml );

                fWriter.close ();
                fWriter = null;

                filePath = psAttachment.getAbsolutePath ();
            }
        }
        catch ( Exception e )
        {
            System.out.println ( "Exception while creating Sales Order Ack html file" );
            e.printStackTrace ();
        }
        finally
        {
            if ( fWriter != null )
            {
                try
                {
                    fWriter.close ();
                    fWriter = null;
                }
                catch ( IOException ignore )
                {
                }
            }
        }

        return filePath;
    }

    public static String formatAsHTML ( String host, SalesOrder salesOrder, ArrayList presentList ) throws ScalarException
    {
        StringBuffer buf = new StringBuffer ( 2098 );
        String heading = null;
        if ( salesOrder.getIsSample() )
        {
            heading = "Sample Order ";
        }
        else
        {
            heading = "Sales Order ";
        }
        buf.append ( "<HTML><HEAD><TITLE>Scalarsoft - ChipTrac</TITLE>" );
        buf.append ( "<LINK href='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/stylesheets/scalarsoft.css' type=text/css rel=stylesheet>" );
        buf.append ( "<style type='text/css'>" );
        buf.append ( "a { text-decoration : none}" );
        buf.append ( "</style>" );
        buf.append ( "</HEAD><BODY bgColor='#ffffff' leftMargin=0 topMargin=0 marginheight='0' marginwidth='0'>" );
        buf.append ( "<!-- from here your body starts -->" );
        buf.append ( "<Div1><table width='98%' cellspacing='0' cellpadding='0' border=0 align=center>" );
        buf.append ( " <tr>" );
        buf.append ( "<td width='34%' align='left' valign='top'><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/scalar_logo.jpg' height='72' width='180' border=0></td>" );
        buf.append ( "<td width='1%'><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif'></td>" );
        Address clientAddress = salesOrder.getClientAddressAsObject ();
        buf.append ( "<td width='30%' align='center' class='NArialL'>");
        buf.append ( "<table border=0 cellspacing='0' cellpadding='0'>" );
        buf.append ( "<tr><td align='center' nowrap><h3>" + heading + "Acknowledgement</h3></td></tr>" );
        buf.append ( "<tr><td align='center' class='NArialL'>" ).append( salesOrder.getClientName() ).append( "</td></tr>" );
        buf.append ( "<tr><td align='center' class='NArialL'>" ).append ( salesOrder.getClientAddressAsHTML() ).append ( "</td></tr>" );
        buf.append ( "</table></td>" );
        
        buf.append ( "<td width='1%'><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif'></td>" );

        buf.append ( " <td width='34%' align=center><font class='NArialW'>" );
        buf.append ( " </font></td>" );
        buf.append ( " </tr>" );
        buf.append ( "<tr><td width='1%'><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif'></td></tr>" );

        String customerName = salesOrder.getCustomerName ();

        Address address = salesOrder.getBillingAddressAsObject ();
		String addressValue = address.getAddressAsString();
        if ( salesOrder.getCustomerName ().equals ( salesOrder.getBillingAddressAsObject().getContactPerson () ) )
        {
            customerName = null;
        }
        buf.append ( " <tr>" );
        buf.append ( " <td height='100%'>" );
        buf.append ( " <table  height='100%' border=1 width='100%' bordercolor='#000000' cellspacing='0' cellpadding='0'>" );
        buf.append ( " <tr height=20><td class='NArialL' bgcolor='#DEE1E2'>Ordered By :</td></tr>" );
        buf.append ( "<tr height=20><td valign='top' class='NArialL' bgcolor='#FFFFEE'>" );
        buf.append ( "<table width='100%' class='NArialL' height=80 cellspacing='0' cellpadding='0'>" );

        buf.append ( "<tr><td>");

        /*if( salesOrder.getBillingAddressAsObject().getContactPerson() != null && salesOrder.getCustomerName().trim().length() !=0 )
        {
            if( ! salesOrder.getBillingAddressAsObject().getContactPerson().equals( salesOrder.getCustomerName() ) )
            {
                 buf.append(customerName + "<br>");
            }
        }*/

		buf.append (  salesOrder.getBillingAddressAsHTML() );
		buf.append ( "</td></tr>"  );
        buf.append ( "</table></td>" );
        buf.append ( "</tr>" );
        buf.append ( "</table>" );
        buf.append ( "</td>" );

        buf.append ( "<td width='1%'><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif'></td>" );
        buf.append ( "<td height='100%'>" );
        buf.append ( " <table height='100%' border=1 width='100%' bordercolor='#000000' cellspacing='0' cellpadding='0'>" );
        buf.append ( " <tr height=20><td class='NArialL' bgcolor='#DEE1E2'>Bill To :</td></tr>" );
        buf.append ( "<tr height=20><td valign='top' class='NArialL' bgcolor='#FFFFEE'>" );
        buf.append ( "<table width='100%' class='NArialL' height=80 cellspacing='0' cellpadding='0'>" );
        buf.append ( "<tr><td>" );
        /*if( salesOrder.getBillingAddressAsObject().getContactPerson() != null && salesOrder.getCustomerName().trim().length() !=0 )
        {
            if( ! salesOrder.getBillingAddressAsObject().getContactPerson().equals( salesOrder.getCustomerName() ) )
            {
                 buf.append(customerName + "<br>");
            }
        }*/
		buf.append (  salesOrder.getBillingAddressAsHTML() + "</td></tr>" );
        buf.append ( "</table></td>" );
        buf.append ( "</tr>" );
        buf.append ( "</table>" );
        buf.append ( "</td>" );

        Address address2 = salesOrder.getShippingAddressAsObject ();

        buf.append ( "<td width='1%'><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif'></td>" );
        buf.append ( "<td height='100%'>" ); //Modified by Krishna Prasad on 6th May 2004 to set All three OrderedBy,BillTo and ShipTo address table same height
        buf.append ( " <table height='100%' border=1 width='100%' bordercolor='#000000' cellspacing='0' cellpadding='0'>" );
        buf.append ( " <tr height=20><td class='NArialL' bgcolor='#DEE1E2'>Ship To :</td></tr>" );
        buf.append ( "<tr height=20><td valign='top' class='NArialL' bgcolor='#FFFFEE'>" );
        buf.append ( "<table width='100%' class='NArialL' height=80 cellspacing='0' cellpadding='0'>" );
        /*buf.append ( "<tr><td>" + salesOrder.getCustomerName () + "<br>" );*/
		buf.append (  salesOrder.getShippingAddressAsHTML() + "</td></tr>" );

        buf.append ( "</table></td>" );
        buf.append ( "</tr>" );
        buf.append ( "</table>" );
        buf.append ( "</td>" );
        buf.append ( "</tr>" );
        buf.append ( "<tr><td colspan=5><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif'></td></tr>" );
        buf.append ( "<tr>" );
        buf.append ( "<td class='NArialL' height='100%'>" );
        buf.append ( "<table width='100%' height='100%'class='NArialL' border=1 bordercolor='#000000' cellspacing='0' cellpadding='0'>" );
        buf.append ( "<tr height=20><td bgcolor='#DEE1E2'> Customer PO#</td><td bgcolor='#DEE1E2'>");

        if ( salesOrder.getIsSample() )
        {
            buf.append ( "Sample Sales Order#");
        }
        else
        {
            buf.append ( "Sales Order#");
        }

        buf.append("</td><td bgcolor='#DEE1E2'>Change #</td></tr>" );
        buf.append ( "<tr height=20><td bgcolor='#FFFFEE'>" + salesOrder.getCustomerPO () + "&nbsp;</td><td bgcolor='#FFFFEE'>" + salesOrder.getSalesOrderNo () + " &nbsp;</td><td bgcolor='#FFFFEE'>" + (SalesOrderDAO.loadChangeNo ( salesOrder.getSalesOrderId () ) - 1) + " &nbsp;</td></tr>" );
        buf.append ( "</table>" );
        buf.append ( "</td>" );
        buf.append ( "<td width='1%'><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif'></td>" );
        buf.append ( "<td class='NArialL' height='100%'>" );
        buf.append ( "<table width='100%' height='100%' class='NArialL' border=1 bordercolor='#000000' cellspacing='0' cellpadding='0'>" );
        buf.append ( "<tr height=20><td bgcolor='#DEE1E2'> Order Date</td><td bgcolor='#DEE1E2'>Ship Via</td></tr>" );
        buf.append ( "<tr height=20><td bgcolor='#FFFFEE'>" + salesOrder.getBookingdateAsString () + "&nbsp;</td><td bgcolor='#FFFFEE'>" + salesOrder.getShippingMethod () + "&nbsp;</td></tr>" );
        buf.append ( "</table>" );
        buf.append ( "</td>" );
        buf.append ( "<td width='1%'><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif'></td>" );
        buf.append ( "<td class='NArialL' height='100%'>" );
        buf.append ( "<table width='100%' height='100%' class='NArialL' border=1 bordercolor='#000000' cellspacing='0' cellpadding='0'>" );
        buf.append ( "<tr height=20><td  bgcolor='#DEE1E2'>Sales Person</td><td bgcolor='#DEE1E2'>Regional Rep</td><td bgcolor='#DEE1E2'>Del Terms</td><td bgcolor='#DEE1E2'>Pay Terms</td></tr>" );
        buf.append ( "<tr height=20><td bgcolor='#FFFFEE'>" + salesOrder.getSalesPerson () + "&nbsp;</td><td bgcolor='#FFFFEE'>" + salesOrder.getRegionalRep () + "&nbsp;</td><td bgcolor='#FFFFEE'>" + salesOrder.getDeliveryTerms () + "&nbsp;</td><td bgcolor='#FFFFEE'>" + ( salesOrder.getShippingTerms ().trim ().equals ( "-1" ) ? "" : salesOrder.getShippingTerms () ) + "&nbsp;</td></tR>" );
        buf.append ( "</table>" );
        buf.append ( "</td>" );
        buf.append ( "</tr>" );
        buf.append ( "<tr><td colspan=5><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif' height=5></td></tR>" );

        buf.append ( "<tr><td colspan=5 class='NArialL'><U>Comments:</U></td></tR>" );
        buf.append ( "<tr><td colspan=5 class='NArialL' bgcolor='#FFFFEE'>" + salesOrder.getComments () + "&nbsp;</td></tR>" );
        buf.append ( "<tr><td colspan=5><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif' height=5></td></tR>" );

        buf.append ( "<tr><td colspan='5'>" );
		int noOfColumns = 14;
        buf.append ( "<table width='100%' border=1 bordercolor='#000000' cellspacing='0' cellpadding='0'>" );
        buf.append ( "<tr height=20>" );
        buf.append ( "<td bgcolor='#DEE1E2' class='NArialL' align=center>PO Line#</td>" );
        buf.append ( "<td bgcolor='#DEE1E2' class='NArialL' align=center>Req Qty</td>" );
        buf.append ( "<td class='NArialL' align=center bgcolor='#DEE1E2'>Remaining Qty</td>" );
        buf.append ( "<td class='NArialL' bgcolor='#DEE1E2' align=center>UM</td>" );
        buf.append ( "<td class='NArialL' bgcolor='#DEE1E2' align=center>" );

		if(ConfigManager.getBooleanProperty(ConfigManager.PROP_SHOW_SALES_LINEITEM_MARKETING_PART_NUMBER)) {
			String mktgPartNumberLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.mktgPartNumberr" );
			if ( mktgPartNumberLabel == null ) {
				mktgPartNumberLabel = Labels.DEFAULT_MKTG_PART_NUMBER_LABEL;
			}
			buf.append (mktgPartNumberLabel);
		} else {
			String mfgPartNumberLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.mfgPartNumber" );
			if ( mfgPartNumberLabel == null ) {
				mfgPartNumberLabel = Labels.DEFAULT_MFG_PART_NUMBER_LABEL;
			}
			buf.append (mfgPartNumberLabel);
		}
		buf.append("</td>");

        String customerPartNumberLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.customerPartNumber" );
        if ( customerPartNumberLabel == null )
        {
            customerPartNumberLabel = Labels.DEFAULT_CUSTOMER_PART_NUMBER_LABEL;
        }

        buf.append ( "<td class='NArialL' bgcolor='#DEE1E2' align=center>" + customerPartNumberLabel + "</td>" );
        buf.append ( "<td class='NArialL' bgcolor='#DEE1E2' align=center>Description</td>" );
        buf.append ( "<td class='NArialL' bgcolor='#DEE1E2' align=center>Requested Dock Date</td>" );
        buf.append ( "<td class='NArialL' bgcolor='#DEE1E2' align=center>Scheduled<br> Ship Date</td>" );
        buf.append ( "<td class='NArialL' bgcolor='#DEE1E2' align=center>Revised<br> Ship Date</td>" );
        buf.append ( "<td bgcolor='#DEE1E2' class='NArialL' align=center>Taxable<br>Yes or No</td>" );
        buf.append ( "<td bgcolor='#DEE1E2' class='NArialL' align=center>Expedite Fee<br>Yes or No</td>" );
        buf.append ( "<td class='NArialL'  bgcolor='#DEE1E2' align=center> Unit <br>Price</td>" );
        buf.append ( "<td class='NArialL'  bgcolor='#DEE1E2' align=center>Extended<br> Price</td>" );

        buf.append ( "</tr>" );

        LineItem lineItem = null;
        ArrayList presentListWithSubtotals = loadLineItemsWithSubTotals ( presentList );
        boolean lineItemsPresent = false;

        for ( int i = 0; i < presentListWithSubtotals.size (); i++ )
        {
            HashMap hashMap = ( HashMap ) presentListWithSubtotals.get ( i );
            Iterator iterator = hashMap.keySet ().iterator ();
            if( !hashMap.isEmpty() ){
                lineItemsPresent = true;
            }
            while ( iterator.hasNext () )
            {
                ArrayList list = ( ArrayList ) iterator.next ();
                SubTotal subTotal = ( SubTotal ) hashMap.get ( list );
                String subTotalQty = subTotal.getSubTotalQty ();
                String subTotalAmt = subTotal.getSubTotalAmt ();

                int size = list.size ();

                for ( int j = 0; j < size; j++ )
                {
                    lineItem = ( LineItem ) list.get ( j );
                    buf.append ( "<tr height=20>" );
                    buf.append ( "<td bgcolor='#FFFFEE'  class='NArialL' align=center>" + lineItem.getPoLineItemNo () + "&nbsp;</td>" );
                    buf.append ( "<td bgcolor='#FFFFEE'  class='NArialL' align=center>" + lineItem.getQuantity () + "&nbsp;</td>" );
                    buf.append ( "<td  align=center  class='NArialL' bgcolor='#FFFFEE'>" + lineItem.getToBeShippedQtyAsString () + "&nbsp;</td><td  class='NArialL' bgcolor='#FFFFEE' align=center>ea</td>" );
                    buf.append ( "<td bgcolor='#FFFFEE'  class='NArialL' align=center nowrap>" );
					if(ConfigManager.getBooleanProperty(ConfigManager.PROP_SHOW_SALES_LINEITEM_MARKETING_PART_NUMBER)) {
						buf.append ( lineItem.getMarketingPartNo ());
					} else {
						buf.append ( lineItem.getManufacturingPartNo ());
					}
					buf.append("&nbsp;</td>");
                    buf.append ( "<td bgcolor='#FFFFEE'  class='NArialL' align=center nowrap>" + lineItem.getCustomerPartNo () + "&nbsp;</td>" );
                    buf.append ( "<td bgcolor='#FFFFEE'  class='NArialL' wrap>" + lineItem.getLineItemDescription () + "&nbsp;</td>" );
                    buf.append ( "<td  class='NArialL' bgcolor='#FFFFEE' align=center>" + lineItem.getRequestDate () + "&nbsp;</td>" );
                    buf.append ( "<td  bgcolor='#FFFFEE'  class='NArialL' align=center>" + lineItem.getScheduleDate () + "&nbsp;</td>" );
                    buf.append ( "<td  bgcolor='#FFFFEE'  class='NArialL' align=center>" + lineItem.getRevisedDate () + "&nbsp;</td>" );
                    buf.append ( "<td  class='NArialL' bgcolor='#FFFFEE' align=center>" + lineItem.getIsTaxableAsString () + "&nbsp;</td>" );
                    buf.append ( "<td  class='NArialL' bgcolor='#FFFFEE' align=center>" + ( ( lineItem.getIsExpedite () == true ) ? "Yes" : "No" ) + "&nbsp;</td>" );
                    buf.append ( "<td  class='NArialL' bgcolor='#FFFFEE' align=center>" + lineItem.getUnitPriceAsString () + "&nbsp;</td>" );
                    buf.append ( "<td  class='NArialL' bgcolor='#FFFFEE' align=right>" + lineItem.getExtendedPriceAsString () + "&nbsp;</td>" );
                    buf.append ( "</tr>" );
                }
                buf.append ( "<tr>" );
                buf.append ( "<td colspan='2'  bgcolor='#FFFFFF' class='NArialL' align='right'>Sub Total</td>" );
                buf.append ( "<td colspan='1' bgcolor='#FFFFFF' class='NArialL' align='center'>" + subTotalQty + "&nbsp;</td>" );
                buf.append ( "<td colspan='").append(noOfColumns-4).append("' >&nbsp;</td>" );
                buf.append ( "<td colspan='1' bgcolor='#FFFFFF' class='NArialL' align='right'>" + subTotalAmt + "&nbsp;</td>" );
                buf.append ( "</tr>" );
            }
        }
        buf.append ( "</table>" );
        if( !lineItemsPresent )
        {
            buf.append ( "<font class='NArialL'><li>All the line items have been cancelled.</font>");
        }
        buf.append ( "</td></tr>" );
        buf.append ( "<tr><td colspan=5><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif' height=5></td></tR>" );

        buf.append ( "<tr><td colspan='5'>" );
        buf.append ( "<table width='35%' border=1 align=left bordercolor='#000000' cellspacing='0' cellpadding='0'>" );
        String end_customer_Label = MessageResources.getMessageResources(Labels.APPLICATION_RESOURCE_PROPERTIES).getMessage("label.sales.endCustomer");
        if ( end_customer_Label == null )
        {
            end_customer_Label = "Error in End_Customer";
        }
        String end_user_Label = MessageResources.getMessageResources(Labels.APPLICATION_RESOURCE_PROPERTIES).getMessage("label.sales.endUser");
        if ( end_user_Label == null )
        {
            end_user_Label = "Error in End_user";
        }
        String quation_no_Label = MessageResources.getMessageResources(Labels.APPLICATION_RESOURCE_PROPERTIES).getMessage("label.sales.quotationNo");
        if ( quation_no_Label == null )
        {
            quation_no_Label = "Error in quation No";
        }
        buf.append ( "<tr><td class='NArialL' bgcolor='#DEE1E2'>"+ end_customer_Label + "</td>");
        buf.append ( "<td class='NArialL' bgcolor='#DEE1E2'>"+ end_user_Label + "</td>");
        buf.append ( "<td class='NArialL' bgcolor='#DEE1E2'>"+ quation_no_Label + "</td></tr>");

        buf.append ( "<tr><td class='NArialL' bgcolor='#FFFFEE'>&nbsp;" + salesOrder.getOdm() + "&nbsp;</td>" );
        buf.append ( "<td class='NArialL' bgcolor='#FFFFEE'>&nbsp;" + salesOrder.getEndCustomer() + "&nbsp;</td>" );
        if ( salesOrder.getQuotationNo() == null  )
        {
            buf.append ( "<td class='NArialL' bgcolor='#FFFFEE'>&nbsp; </td></tR>" );
        }
        else
        {
            buf.append ( "<td class='NArialL' bgcolor='#FFFFEE'>&nbsp;" + salesOrder.getQuotationNo() + "&nbsp;</td></tR>" );
        }
        buf.append ( "</table>" );

        buf.append ( "<table width='25%' border=1 align=right bordercolor='#000000'  cellspacing='0' cellpadding='0'>" );
        buf.append ( "<tr><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/spacer.gif' height=5></td></tR>" );
        buf.append ( "<tr>" );
        buf.append ( "<td bgcolor='#DEE1E2' class='NArialL'>Total</td><td bgcolor='#DEE1E2' class='NArialL'  align='right'>" + salesOrder.getFinalSubTotalAsString () + "</td>" );
        buf.append ( "</tr>" );
        buf.append ( "<tr><td bgcolor='#DEE1E2' class='NArialL'>Sales Tax</td><td bgcolor='#DEE1E2'  class='NArialL' align='right'>" + salesOrder.getFinalSalesTaxAsString () + "</td>" );
        buf.append ( "</tr>" );
        buf.append ( "<tr><td bgcolor='#DEE1E2' class='NArialL'>Freight</td><td bgcolor='#DEE1E2'  class='NArialL' align='right'>" + salesOrder.getFrieghtAsString () + "</td>" );
        buf.append ( "</tr>" );
        buf.append ( "<tr><td bgcolor='#DEE1E2' class='NArialL'>" + salesOrder.getMiscName () + "</td><td class='NArialL' bgcolor='#DEE1E2' align='right'>" + salesOrder.getMiscAsString () + "</td>" );
        buf.append ( "</tr>    " );
        buf.append ( "<tr><td bgcolor='#DEE1E2' class='NArialL'>Balance Due</td><td  class='NArialL' bgcolor='#DEE1E2' align='right'>" + salesOrder.getFinalOrderTotalAsString () + "</td>" );
        buf.append ( "</tr>    " );
        buf.append ( "</table></td></tr>" );
        buf.append ( "</table>" );
        if(ConfigManager.getShowTermsLabel())
        {
            buf.append ( "<table width='98%' bordercolor='#000000' cellspacing='0' cellpadding='2' border=0 align='center'>");
            buf.append ( "<TR>");
            buf.append ( "<TD width='98%' class='NArialRS'><p>" + Constants.TERMS_LABEL + "</p></TD>");
            buf.append ( "</TR>");
            buf.append ( "</table>");
        }
        buf.append ( "</td></tr>    " );
        buf.append ( "</p>" );
        if (ConfigManager.getShowTermsFromDB())
        {
        buf.append ( "<div style='page-break-after: always;'>&nbsp;</div><table width='100%' cellspacing='5' cellpadding='0' border=0 align=center>" );
        buf.append ( "<TR>" );
        buf.append ( "<TD width='100%' valign='top' colspan='3' class='viewdata2'><center><b>Terms And Conditions</b></center></TD>" );
        buf.append ( "</TR>" );
        buf.append ( "<TR>" );
        buf.append ( "<TD width='100%' valign='top' colspan='3' class='viewdata2'><center>" + salesOrder.getClientName () + "<BR>" );
        buf.append ( SalesOrder.getClientAddressToLoad ( clientAddress ) + "</center></TD>" );
        buf.append ( "</TR>" );
        buf.append ( "<TR>" );
        buf.append ( "<TD width='100%' colspan='3' class='viewdata1'>&nbsp;</TD>" );
        buf.append ( "</TR>" );
        buf.append ( "<tr>" );

        ArrayList list = SalesDAO.loadTermsAndConditionsAsList ();
        if ( list != null )
        {
            for ( int i = 0; i < list.size (); i++ )
            {
                TermsAndConditions terms = ( TermsAndConditions ) list.get ( i );
                buf.append ( "<tr><td bgcolor='#DEE1E2' class='viewdata1'><U>" + ( i + 1 ) + ".&nbsp;" );
                buf.append ( terms.getTermsTitle ().trim () + "</U>" + "&nbsp;" + terms.getTerms ().trim () + "</td></tr>" );
            }//for

        }//if


        buf.append ( "</tr></table>" );
        }
        else
        {
            buf.append ( "<p STYLE='page-break-after: always'></p>" );
            buf.append ( "<table width='98%' bordercolor='#000000' border='0' cellspacing='0' cellpadding='0' align='center'><TR>");
            buf.append ( "<TD width='100%' valign='top'><img src='http://" + host + "/" + ConfigManager.getChipTracContext () + "/jsp/includes/images/Terms and Condition of Sale.jpg' width='1000'/></TD></TR></table>");
        }
        buf.append ( "</body></html>" );

        return buf.toString ();
    }

    //The line items based on Manufacturing Part Nos and calculates SubTotals.
    public static ArrayList loadLineItemsWithSubTotals ( ArrayList lineItemList )
    {
        ArrayList list = new ArrayList ();
        LinkedHashMap hash = new LinkedHashMap ();
        for ( int i = 0; i < lineItemList.size (); i++ )
        {
            LineItem lineItem = ( LineItem ) lineItemList.get ( i );
            String mfgPartNumber = lineItem.getManufacturingPartNo ();
            if ( !( hash.containsKey ( mfgPartNumber ) ) )
            {
                hash.put ( mfgPartNumber, new ArrayList () );
            }
            ArrayList arrList = ( ArrayList ) hash.get ( mfgPartNumber );
            arrList.add ( lineItem );
        }
        Iterator iterator = hash.keySet ().iterator ();
        LinkedHashMap hashMap = new LinkedHashMap ();

        while ( iterator.hasNext () )
        {
            String str = ( String ) iterator.next ();
            ArrayList arrList = ( ArrayList ) hash.get ( str );
            SubTotal subTotal = new SubTotal();

            double subTotalAmt = 0.0;
            int subTotalQty = 0;
                for ( int i = 0; i < arrList.size (); i++ )
                {
                    subTotalAmt = subTotalAmt + ( ( LineItem ) arrList.get ( i ) ).getExtendedPriceAsDouble();
                    subTotalQty = subTotalQty + ( ( LineItem ) arrList.get ( i ) ).getToBeShippedQty();
                }
            subTotal.setSubTotalQty ( Integer.toString ( subTotalQty ) );
            subTotal.setSubTotalAmt ( StringUtils.formatAmountWithNoOfDecimals( subTotalAmt) );
            hashMap.put ( arrList, subTotal );
        }
        list.add ( hashMap );

        return list;
    }

    public static ArrayList loadLineItemsWithSubTotalsForAirgo ( ArrayList lineItemList )
    {
        ArrayList list = new ArrayList ();
        LinkedHashMap hash = new LinkedHashMap ();
        for ( int i = 0; i < lineItemList.size (); i++ )
        {
            LineItem lineItem = ( LineItem ) lineItemList.get ( i );
            String mfgPartNumber = lineItem.getManufacturingPartNo ();
            if ( !( hash.containsKey ( mfgPartNumber ) ) )
            {
                hash.put ( mfgPartNumber, new ArrayList () );
            }
            ArrayList arrList = ( ArrayList ) hash.get ( mfgPartNumber );
            arrList.add ( lineItem );
        }

        Iterator iterator = hash.keySet ().iterator ();
        LinkedHashMap hashMap = new LinkedHashMap ();

        while ( iterator.hasNext () )
        {
            String str = ( String ) iterator.next ();
            ArrayList arrList = ( ArrayList ) hash.get ( str );
            SubTotal subTotal = new SubTotal();

            double subTotalAmt = 0.0;
            int subTotalQty = 0;
            for ( int i = 0; i < arrList.size (); i++ )
            {
                subTotalAmt = subTotalAmt + ( ( LineItem ) arrList.get ( i ) ).getExtendedPriceAsDouble();
                subTotalQty = subTotalQty + ( ( LineItem ) arrList.get ( i ) ).getQuantity() ;
            }
            subTotal.setSubTotalQty ( Integer.toString ( subTotalQty ) );
            subTotal.setSubTotalAmt ( StringUtils.formatAmountWithNoOfDecimals ( subTotalAmt ) );

            hashMap.put ( arrList, subTotal );
        }
        list.add ( hashMap );

        return list;
    }



    public static String coolstatus = null;
}

